package com.weixiaodong.javabasic.Java中的浮点数;

/**
 * 浮点数转化为二进制
 */
@SuppressWarnings("all")
public class DecimalToBinary {

    public static String decimal2Binary(double var) {
        String s = Double.toString(var);
        String[] split = s.split("\\."); // 注意：转义
        String IntegerPart = split[0];
        String doublePart = split[1];
        StringBuilder bin = new StringBuilder();
        int a = Integer.parseInt(IntegerPart);
        double b = Double.parseDouble("0." + doublePart);
        bin.append(int2Binary(a));
        bin.append(".");
        bin.append(double2Binary(b));
        return bin.toString();
    }

    public static String int2Binary(int var) {
        StringBuilder bin = new StringBuilder();
        while (var > 1) {
            bin.append(var % 2);
            var /= 2;
        }
        if (var != 0) {
            bin.append(var);
        }
        return bin.reverse().toString();
    }

    // 不带有整数部分的double类型
    public static String double2Binary(double var) {
        StringBuilder bin = new StringBuilder();
        while (var < (double) 1.0) {
            var *= 2;
            if (var < 1.0) {
                bin.append("0");
            } else {
                String s = String.valueOf(var);
                String[] split = s.split("\\.");
                bin.append(split[0]);
                var = Double.parseDouble("0." + split[1]);
            }
        }
        bin.append(String.valueOf(var));
        return bin.toString();
    }


    public static void main(String[] args) {
       //  System.out.println(decimal2Binary(0.875));

        System.out.println(decimal2Binary(0.875));
    }
}
